<template>
  <el-dialog v-model="dialogVisible" title="卡片详情" @close="closeDialog">
    <b>当前数字：{{ currentValue }}</b>
    <el-button type="primary" @click="increaseValue" style="margin-left: 10px">增加</el-button>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, watch, defineExpose } from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
  name: 'CardDialog',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    cardId: {
      type: Number,
      required: true,
    },
  },
  emits: ['update:visible'],
  setup(props, { emit }) {
    const store = useStore()
    const dialogVisible = ref(props.visible)
    const currentValue = ref(0)

    // 监听 props.visible 的变化
    watch(
      () => props.visible,
      (newVal) => {
        dialogVisible.value = newVal
      },
    )

    // 监听 props.cardId 的变化
    watch(
      () => props.cardId,
      (newCardId) => {
        const card = store.getters['cards/cards'].find((c: any) => c.id === newCardId)
        if (card) {
          currentValue.value = card.value
        }
      },
      { immediate: true },
    )

    // 增加数字并更新 store
    const increaseValue = () => {
      const newValue = currentValue.value + 1
      store.dispatch('cards/updateCardValue', { id: props.cardId, value: newValue })
      currentValue.value = newValue
    }

    // 关闭对话框时通知父组件
    const closeDialog = () => {
      dialogVisible.value = false
      emit('update:visible', false)
    }

    return {
      dialogVisible,
      currentValue,
      increaseValue,
      closeDialog,
    }
  },
})
</script>

<style scoped></style>
